import cv2

# 图片识别方法封装


def discern(img):
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    cap = cv2.CascadeClassifier(
        "G:\Python35\Lib\site-packages\opencv_python-3.4.1.dist-info\haarcascades\haarcascade_frontalface_default.xml"
    )

    faceRects = cap.detectMultiScale(
        gray,
        scaleFactor=1.2,
        minNeighbors=3,
        minSize=(50, 50)
    )

    if len(faceRects):
        for faceRect in faceRects:
            x, y, w, h = faceRect
            # 框出人脸
            cv2.rectangle(img, (x, y), (x + h, y + w), (0, 255, 0), 2)
    cv2.imshow("Image", img)


cap = cv2.VideoCapture(0)

while 1:
    ret, img = cap.read()
    discern(img)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# 释放摄像头
cap.release()
# 释放窗口资源
cv2.destroyAllWindows()


